package com.hpf.gupao.pattern.prototype;

import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;
import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;

import java.io.*;
import java.util.List;

/**
 * @description:
 * @datetime: 2021/5/19 21:13
 * @author: huangpengfei
 */
public class ConcretePrototypeA implements Serializable, Cloneable, Prototype {

    private int age;

    private String name;

    private List<String> hobbies;

    @Override
    public Prototype deepClone() {
        try{
            // 将对象写到内存中，深克隆
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(bos);
            objectOutputStream.writeObject(this);

            // 从内存中读取字节
            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream objectInputStream = new ObjectInputStream(bis);
            ConcretePrototypeA concretePrototypeB = (ConcretePrototypeA)objectInputStream.readObject();
            objectInputStream.close();
            return concretePrototypeB;
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 浅克隆
     * @return
     */
    @Override
    protected Prototype clone(){
        ConcretePrototypeA concretePrototypeA = new ConcretePrototypeA();
        concretePrototypeA.setAge(this.age);
        concretePrototypeA.setName(this.name);
        concretePrototypeA.setHobbies(this.hobbies);
        return concretePrototypeA;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<String> getHobbies() {
        return hobbies;
    }

    public void setHobbies(List<String> hobbies) {
        this.hobbies = hobbies;
    }
}
